import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 收集器
 * git地址

 https://gitee.com/yujianlong1988/java8andDisruptor.git
 * @author yujianlong
 * @create 2018-06-16 11:29
 **/
public class ParallelStreamTest1 {

	@Test
	public void paralleltest1() {//并行流求和1-100的和
		Integer reduce = Stream.iterate(1, i -> i + 1).limit(100).parallel().reduce(0, Integer::sum);

		System.out.println(reduce);

		int sum = IntStream.rangeClosed(1, 100).sum();
		System.out.println(sum);
		int sum1 = IntStream.rangeClosed(1, 100).parallel().sum();
		System.out.println(sum1);
	}

	@Test
	public void paralleltest2() {//并行流不使用的场景-线程不安全
//		List<Integer> container = new ArrayList<>();
//		List<Integer> container = new CopyOnWriteArrayList<>();
		Queue<Integer> container = new ConcurrentLinkedDeque<>();
		IntStream.rangeClosed(1, 100).boxed().parallel().forEach(container::add);
		System.out.println(container);
		System.out.println(container.size());

	}

	@Test
	public void paralleltest3() {//并行流多线程的简单应用
		long start = System.currentTimeMillis();
		System.out.println();
		IntStream.rangeClosed(1, 10).boxed().parallel().forEach(i->{
					System.out.println(i);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

		);
		long end = System.currentTimeMillis();
		System.out.println(end-start);
		//串行就10秒 并行就2秒 可以想象成我们有一个数据集合，要并行处理


	}

	public static void doSomething(Callable call){
		try {
			System.out.println(call.call());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void doSomething(Supplier supplier){
		try {
			System.out.println(supplier.get());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Test
	public void paralleltest4() {//强制转换
		Callable<Integer> call1 = () -> {
			return 1;
		};

		Supplier<Integer> supplier = () -> {
			return 1;
		};

		doSomething((Supplier) ()->1);

	}

	







}
